<template>
  <div v-show="showModal" @click.stop="closeSharePost" class="c-flex-column c-justify-center c-pf c-p-t0 c-p-l0 c-p-r0 c-pz101 c-h c-w100 c-maxw640 c-translucent-balck60">
    <div>
      <img @click.stop="clickImg" src="" class="c-w80 c-br8 c-m-0auto" id="spreadImg" />
    </div>
    <div class="c-mt20">
      <div class="c-w80 c-hh60 c-br8 c-m-0auto c-bg-white c-flex-row c-justify-center c-aligni-center" @click.stop="showShareMasker">
        <span class="c-fs24">分享活动</span>
      </div>
    </div>
  </div>
</template>

<script>
  const CANVAS_WIDTH = 640;
  const CANVAS_HEIGHT = 1017;
  const CUR_TIMETAMP = new Date().getTime();
  export default {
    name: "DaySign",
    props: {
      showSharePost: {
        type: Boolean,
        default: false
      },
      sharePostInfo: {
        type: Object,
        default: function () {
          return {}
        }
      }
    },
    beforeCreate() { },
    data() {
      return {
        showModal: false,
        shareInfo: null
      };
    },

    computed: {},
    watch: {
      showSharePost(val) {
        this.showModal = val;
      },
      sharePostInfo(val) {
        if (Object.keys(val).length > 0) {
          this.shareInfo = val;
          this.startCanvas();
        }
      }
    },
    methods: {
      startCanvas() {
        let that = this;
        let canvas = document.createElement("canvas");
        canvas.width = CANVAS_WIDTH;
        canvas.height = CANVAS_HEIGHT;
        let ctx = canvas.getContext("2d");
        //开始绘制图片
        that.downImg(that.shareInfo.shareImg)
          .then(signBgImg => {
            //绘制背景图片
            ctx.save();
            ctx.drawImage(signBgImg, 0, 0, CANVAS_WIDTH, 853);
            signBgImg = null;
            ctx.restore();
            //绘制活动标题
            let titleLabel = {
              fontSize: 34,
              bold: true,
              fontColor: that.shareInfo.fontColor,
              textAlign: "center",
              textBaseline: 'top',
              textStr: that.shareInfo.name,
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 60
            };
            that.drawText(ctx, titleLabel);
            //绘制活动描述
            let wordArr = [];
            let firstLine = that.shareInfo.proTxt[0];
            let secondLine = that.shareInfo.proTxt[1];
            let thirdLine = that.shareInfo.proTxt[2];
            firstLine && wordArr.push({
              content: firstLine
            });
            secondLine && wordArr.push({
              content: secondLine
            });
            secondLine && wordArr.push({
              content: thirdLine
            });
            let wordArrLength = wordArr.length;
            for (let i = 0; i < wordArrLength; i++) {
              let titleDec = {
                fontSize: 28,
                fontColor: that.shareInfo.fontColor,
                textAlign: "center",
                textBaseline: 'top',
                textStr: wordArr[i].content,
                offsetX: CANVAS_WIDTH / 2,
                offsetY: that.shareInfo.name ? (138 + i * 40) : (60 + i * 40)
              };
              that.drawText(ctx, titleDec);
            }
            // let timeLabel = {
            //   fontSize: 28,
            //   fontColor: that.shareInfo.fontColor,
            //   textAlign: "center",
            //   textBaseline: 'top',
            //   textStr: thirdLine,
            //   offsetX: CANVAS_WIDTH / 2,
            //   offsetY: that.shareInfo.name ? 239 : 159
            // };
            // that.drawText(ctx, timeLabel);
            //绘制底部正方形
            ctx.fillStyle = "#fff";
            let rectInfo = {
              width: CANVAS_WIDTH,
              height: 283,
              offsetX: 0,
              offsetY: 853,
              r: 0
            };
            that.drowRoundRect(ctx, rectInfo);
            ctx.fill();
            return that.downImg(that.shareInfo.qrcodeUrl);
          })
          .then(qrCodeImg => {
            //绘制二维码
            ctx.drawImage(qrCodeImg, 30, 873, 124, 124);
            qrCodeImg = null;
            //绘制分享文本
            let shareOffsetY = 888;
            let shareWord = (that.shareInfo.isShowRecommender ? that.shareInfo.nickname : '你的朋友') + "邀请你一起学习";
            let shareArr = [];
            // let firstLine = shareWord.substring(0, 16);
            // let secondLine = shareWord.substring(16, 32);
            // firstLine && shareArr.push({
            //   content: firstLine
            // });
            // secondLine && shareArr.push({
            //   content: secondLine
            // });
            shareArr = that.drawTextLines(ctx, shareWord, 170);
            let shareArrLength = shareArr.length;
            for (let i = 0; i < shareArrLength; i++) {
              let shareText = null;
              shareText = {
                fontSize: 26,
                fontColor: "#333333",
                textAlign: "left",
                textBaseline: 'top',
                textStr: shareArr[i],
                offsetX: 180,
                offsetY: shareOffsetY + i * 40
              };
              // }
              that.drawText(ctx, shareText);
            }
            let longClickOffsetY = 965;
            //绘制长按识别二维码
            let longClickText = {
              fontSize: 22,
              fontColor: "#999999",
              textAlign: "left",
              textBaseline: 'top',
              textStr: "长按识别二维码或保存图片",
              offsetX: 180,
              offsetY: longClickOffsetY
            };
            that.drawText(ctx, longClickText);
            that.canvasToImage(ctx);
          }).catch(function (error) {
            console.log(error);
            // 处理前面三个Promise产生的错误
          });
      },

      clickImg() { },
      showShareMasker() {
        this.$emit("showShareMasker");
      },
      closeSharePost() {
        this.$emit("closeSharePost");
      },
      //下载图片
      downImg(imgUrl) {
        return new Promise(function (resolve, reject) {
          let img = new Image();
          if (!imgUrl.includes('base64')) {
            img.crossOrigin = "anonymous";
            imgUrl = imgUrl.includes('?') ? `${imgUrl}&t=${CUR_TIMETAMP}` : `${imgUrl}?t=${CUR_TIMETAMP}`;
          }
          img.src = imgUrl;
          img.onload = function () {
            resolve(img);
          };
          img.onerror = function (e) {
            console.log("下载图片失败");
            console.log(imgUrl);
            reject(e);
          };
        });
      },

      //绘制文字
      drawText(ctx, fontInfo, fWidth = 500) {
        ctx.save();
        ctx.fillStyle = fontInfo.fontColor;
        ctx.textBaseline = fontInfo.textBaseline || 'middle';
        ctx.textAlign = fontInfo.textAlign;
        if (fontInfo.bold) {
          ctx.font = 'bold ' + fontInfo.fontSize + "px Helvetica Neue,Helvetica,Roboto,Arial,sans";
        } else {
          ctx.font = fontInfo.fontSize + "px Helvetica Neue,Helvetica,Roboto,Arial,sans";
        }
        ctx.fillText(
          fontInfo.textStr,
          fontInfo.offsetX,
          fontInfo.offsetY,
          fWidth
        );
        ctx.restore();
      },
      //绘制圆角矩形
      drowRoundRect(ctx, rectIbfo) {
        let width = rectIbfo.width;
        let height = rectIbfo.height;
        let offsetX = rectIbfo.offsetX;
        let offsetY = rectIbfo.offsetY;
        let r = rectIbfo.r;
        if (width < 2 * r) { r = width / 2; }
        if (height < 2 * r) { r = height / 2; }
        ctx.beginPath();
        ctx.moveTo(offsetX + r, offsetY);
        ctx.arcTo(offsetX + width, offsetY, offsetX + width, offsetY + height, r);
        ctx.arcTo(offsetX + width, offsetY + height, offsetX, offsetY + height, r);
        ctx.arcTo(offsetX, offsetY + height, offsetX, offsetY, r);
        ctx.arcTo(offsetX, offsetY, offsetX + width, offsetY, r);
        ctx.closePath();
      },

      //获取文字宽度
      getTextWidth(ctx, fontInfo) {
        ctx.save();
        ctx.font = fontInfo.fontSize + "px Helvetica Neue,Helvetica,Roboto,Arial,sans";
        ctx.fillStyle = fontInfo.fontColor;
        ctx.textBaseline = fontInfo.textBaseline || 'middle';
        ctx.textAlign = fontInfo.textAlign;
        let width = ctx.measureText(fontInfo.textStr).width;
        ctx.restore();
        return width;
      },

      //将canvas转成图片
      canvasToImage(ctx) {
        try {
          var dataURL = ctx.canvas.toDataURL("image/jpg");
          let ig = document.getElementById("spreadImg");
          ig.setAttribute("src", dataURL);
          this.$emit("canvasOver");
        } catch (err) {
          console.log("canvas转成图片失败");
          console.log(err);
        }
      },
      drawTextLines(context, t, w) {
        var chr = t.split("");
        var temp = "";
        var row = [];
        for (var a = 0; a < chr.length; a++) {
          if (context.measureText(temp).width < w && context.measureText(temp + (chr[a])).width <= w) {
            temp += chr[a];
          } else {
            row.push(temp);
            temp = chr[a];
          }
        }
        row.push(temp);
        return row;
      }
    },
    activated() {},
    deactivated() { }
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
